from datetime import datetime, timedelta, timezone
import hashlib
from fastapi import APIRouter, Depends, HTTPException, status

import re

from auth.jwt import create_token, decode_token
from mysql.connection import get_connection
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from routers.user.userModels import UserChangePasswordModel, UserLoginModel, UserRegisterModel, UserChengeUsernameModel, UserDeleteModel, UserAddEmailModel, UserChangeEmailModel, UserForgetPasswordModel


router = APIRouter()


@router.post("/login")
async def __login(user_login_form: OAuth2PasswordRequestForm = Depends()):#dirty=1不能登录
    if user_login_form.username == None or user_login_form.password == None:
        return {
            "success": True,
            "code": 1,
            "detail": "用户id或密码不完整"
        }
    connection = get_connection()
    with connection.cursor() as cursor:
        sql = "SELECT * FROM users WHERE username=%s and dirty=0"
        print(user_login_form.username, user_login_form.password)
        cursor.execute(sql, user_login_form.username)
        result = cursor.fetchall()
        print(result)
        if len(result) == 0:
            # return {
            #     "success": True,
            #     "code": "2",
            #     "detal": "该账户不存在"
            # }
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="该账户不存在",
                headers={"WWW-Authenticate": "Bearer"},
            )
        if len(result) > 1:
            return {
                "success": True,
                "code": "3",
                "detail": "该账户存在问题，请联系管理员解决"
            }
    access_token = create_token({
        "id": result[0]["id"],
        "username": result[0]["username"],
        # 一个用户可能有多个角色
        "roles": ["admin"]
    }, timedelta(minutes=30))
    roles = []
    if result[0]["privilege_manage_user"] == 1:
        roles.append("privilege_manage_user")
    return {
        "success": True,
        "access_token": access_token,
        "token_type": "bearer",
        "data": {
            "username": result[0]["username"],
            # 一个用户可能有多个角色
            "roles": ["admin"],
            "accessToken": access_token,#"eyJhbGciOiJIUzUxMiJ9.admin",
            "refreshToken": "eyJhbGciOiJIUzUxMiJ9.adminRefresh",
            "expires": (datetime.now(timezone.utc) + timedelta(minutes=15)).__str__()
        }
    }

@router.post("/register")
async def __register(user_register_model: UserRegisterModel):
    if user_register_model.username == None or user_register_model.password == None:
        return {
            "code": 1,
            "detail": "用户名密码不完整"
        }
    connect = get_connection()
    with connect.cursor() as cursor:
        sql = "INSERT INTO users(username, password) VALUES(%s, SHA2(%s, 256))"
        try:
            cursor.execute(sql, (user_register_model.username, user_register_model.password))
            return {
                "code": 0,
                "data": {
                    "access_token": "随便写",
                    "refresh_token": "以后再说"
                }
            }
        except:
            return {
                "code": 2,
                "detail": "注册失败，请重试"
            }
        

@router.post("/change_username")######################################################判断id是否存在再进行修改
async def __change_username(user_change_username: UserChengeUsernameModel, token: dict = Depends(decode_token)):#前端直接传入id，并不需要用户输入。
    if user_change_username.newUsername == None:
        return {
            "code": 1,
            "detail": "用户名不能为空"
        }
    connect = get_connection()
    with connect.cursor() as cursor:
        sql = "SELECT * FROM users WHERE id=%s"
        cursor.execute(sql, user_change_username.id.__str__())#判断id是否存在
        result = cursor.fetchall()
        if len(result) == 0:
            return {
                "code": 2,
                "detail": "用户不存在。。。"
            }

        sql = "UPDATE users SET username=%s WHERE id=%s"
        try:
            cursor.execute(sql, (user_change_username.newUsername, user_change_username.id.__str__()))#更新用户名
            return {
                "code": 0,
                "data": {
                    "access_token": "随便写",
                    "refresh_token": "以后再说"
                }
            }
        except:
            return {
                "code": 3,
                "detail": "修改失败，请重试"
            }


@router.post("/change_password")######################################################判断id是否存在再进行修改
async def __change_password(user_change_password_model: UserChangePasswordModel, token: dict = Depends(decode_token)):#前端限制id字段，用户不再输入，由前端直接传入后端
    if user_change_password_model.oldPassword == None or user_change_password_model.newPassword == None:
        return {
            "code": 1,
            "detail": "新密码或旧密码不完整"
        }
    connect = get_connection()
    with connect.cursor() as cursor:
        sql = "SELECT * FROM users WHERE id=%s and dirty=0"
        cursor.execute(sql, user_change_password_model.id.__str__())#判断id是否存在
        result = cursor.fetchall()
        if len(result) == 0:
            return {
                "code": 2,
                "detail": "用户不存在。。。"
            }
    
        hash_object = hashlib.sha256()
        hash_object.update(user_change_password_model.oldPassword.encode("UTF-8"))
        old_password = hash_object.hexdigest()####sha256加密密码
        hash_object.update(user_change_password_model.newPassword.encode("UTF-8"))
        new_password = hash_object.hexdigest()

        sql = "SELECT password FROM users WHERE id=%s and dirty=0"
        cursor.execute(sql, user_change_password_model.id.__str__())
        result = cursor.fetchall()
        if result[0]["password"] != old_password:#对照用户输入的原密码是否一致
            return {
                "code": 3,
                "detail": "原密码不正确"
            }
        
        if result[0]["password"] == new_password:
            return {
                "code": 5,
                "detail": "新密码不能与原密码相同"
            }

        sql = "UPDATE users SET password=SHA2(%s, 256) WHERE id=%s"
        try:
            cursor.execute(sql, (user_change_password_model.newPassword, user_change_password_model.id.__str__()))
            return {
                "code": 0,
                "data": {
                    "access_token": "随便写",
                    "refresh_token": "以后再说"
                }
            }
        except:
            return {
                "code": 4,
                "detail": "更新失败，请重试"
            }


@router.post("/delete_user")#####判断当前用户是否有删除权限？？？？
async def __delete_user(user_delete_model: UserDeleteModel, token: dict = Depends(decode_token)):#前端询问是否删除？
    if user_delete_model.id == None:
        return {
            "code": 1,
            "detail": "请输入id"
        }
    connect = get_connection()
    with connect.cursor() as cursor:
        sql = "SELECT * FROM users WHERE id=%s AND dirty=0"###判断用户是否存在
        cursor.execute(sql, user_delete_model.id.__str__())
        result = cursor.fetchall()
        if len(result) == 0:
            return {
                "code": 2,
                "detail": "用户不存在"
            }

        if result[0]["privilege_manage_user"] == 1: ##判断是否为管理员
            return {
                "code": 3,
                "detail": "不允许删除管理员用户"
            }

        sql = "UPDATE users SET dirty=1 WHERE id=%s"
        try:
            cursor.execute(sql, user_delete_model.id.__str__())
            return {
                "code": 0,
                "data": {
                    "access_token": "随便写",
                    "refresh_token": "以后再说"
                }
            }
        except:
            return {
                "code": 4,
                "detail": "删除失败，请重试。。。"
            }


@router.post("/add_email")
async def __add_email(user_add_email_model: UserAddEmailModel, token: dict = Depends(decode_token)):
    if user_add_email_model.email == None or user_add_email_model.id == None:
        return {
            "code": 1,
            "detail":"id或邮箱输入不完整"
        }
    connect = get_connection()
    # str = r'/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/'
    # if not(re.match(str, user_add_email_model.email)):#验证邮箱格式
    #     return {
    #         "code": 3,
    #         "detail": "请输入正确的邮箱格式"
    #     }
    
    with connect.cursor() as cursor:
        sql = "UPDATE users SET mail=%s WHERE id=%s"
        try:
            cursor.execute(sql, (user_add_email_model.email, user_add_email_model.id.__str__()))
            return {
                "code": 0,
                "data": {
                    "access_token": "随便写",
                    "refresh_token": "以后再说"
                }
            }
        except:
            return {
                "code": 2,
                "detail": "添加失败，请重试"
            }



@router.post("/change_email")
async def __change_email(user_change_email_model: UserChangeEmailModel, token: dict = Depends(decode_token)):
    pass


@router.post("/forget_password")
async def __forget_password(user_forget_password_model: UserForgetPasswordModel, token: dict = Depends(decode_token)):
    pass